package com.leyou.second.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.leyou.client.item.ItemClient;
import com.leyou.common.auth.pojo.UserHolder;
import com.leyou.common.auth.pojo.UserInfo;
import com.leyou.common.constants.LyConstants;
import com.leyou.common.constants.MQConstants;
import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpuDTO;
import com.leyou.item.pojo.Brand;
import com.leyou.item.pojo.Category;
import com.leyou.second.dto.SkusDto;
import com.leyou.second.mapper.SecondMapper;
import com.leyou.second.mapper.SkuMapper;
import com.leyou.second.pojo.Second;
import com.leyou.second.pojo.Sku;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 秒杀service
 *
 * @Classname: [ SecondService ]
 * @Date: [ 2020/11/17 12:11 ]
 * @Author: by [ g_s ]
 * @Version: [v1.0]
 */
@Service

public class SecondService {
    @Autowired
    private ItemClient itemClient;
    @Value("${ly.static.itemTemplate}")
    private String itemTemplate; //静态目标名称
    @Value("${ly.static.itemDir}")
    private String itemDir; //静态页面存储路径
    @Autowired(required = false)
    private SkuMapper skuMapper;
    @Autowired(required = false)
    private SecondMapper secondMapper;
    @Autowired
    private SpringTemplateEngine templateEngine;
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;

    // 获取秒杀商品列表
    public List<SkusDto> getSkusList() {
        ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
        // 从缓存中拿出列表
        String skusList = valueOperations.get("SECKILL_SKUS_LIST");
        String skusId = valueOperations.get("SECKILL_SKUS_ID");

        List<Second> secondList = null;
        List<Sku> skuList = null;
        if (skusList == null || skusId == null) { // 如果没有就去数据库拿
            // 查询出所有的秒杀商品的ID
            secondList = secondMapper.selectList(null);
            valueOperations.set("SECKILL_SKUS_ID", JsonUtils.toString(secondList));
            QueryWrapper<Sku> skuQuery = Wrappers.query();
            // 查出sku的信息
            skuQuery.in("id", secondList.stream().map(Second::getSkuId).collect(Collectors.toList()));
            skuList = skuMapper.selectList(skuQuery);
            // 转成json字符串保存到缓存中
            valueOperations.set("SECKILL_SKUS_LIST", JsonUtils.toString(skuList));
        } else {
            secondList = JsonUtils.toList(skusId, Second.class);
            skuList = JsonUtils.toList(skusList, Sku.class);
        }
        // 把sku信息复制到skudto中去
        List<SkusDto> skusDtos = skuList.stream().map(this::skuToSkuDto).collect(Collectors.toList());
        // 复制
        for (int i = 0; i < skusDtos.size(); i++) {
            skusDtos.get(i).setDiscount(secondList.get(i).getDiscount());
            skusDtos.get(i).setDestock(secondList.get(i).getDestock());
        }

        return skusDtos;
    }

    private SkusDto skuToSkuDto(Sku sku) {
        return BeanHelper.copyProperties(sku, SkusDto.class);
    }


    public Map<String, Object> seckillSer(Long id) {
        Map<String, Object> seckill = seckill(id);
        File file = new File(itemDir + "/" + id + ".html");
        if (!file.exists()) {
            this.createStaticPage(id);
        }
        return seckill;
    }

    public Map<String, Object> seckill(Long id) {
        //1.定义Map集合，用于封装所有页面需要的数据
        Map<String, Object> resultMap = new HashMap<>();

        //2.查询并封装数据
        Sku sku = skuMapper.selectById(id);
        SkusDto skusDto = this.skuToSkuDto(sku);
        // 封装秒杀表数据
        Second second = secondMapper.selectById(id);
        skusDto.setDiscount(second.getDiscount());
        skusDto.setDestock(second.getDestock());


        SpuDTO spuDTO = itemClient.findSpuById(skusDto.getSpuId());

        //2.4 根据分类id查询规格组
        List<SpecGroupDTO> specGroupDTOS = itemClient.findSpecGroupDtoByCid(spuDTO.getCid3());

        //3.把查询的数据封装到resultMap中，并返回
        resultMap.put("skuDto", skusDto);
        resultMap.put("detail", spuDTO.getSpuDetail());
        return resultMap;
    }

    /**
     * 生成秒杀商品详情静态页
     */
    public void createStaticPage(Long spuId) {
        //1.创建Context对象
        Context context = new Context();
        //设置动态数据
        context.setVariables(this.seckill(spuId));

        //2.读取静态目标页面（默认会到resources/templates/目录下读取该模板页面）
        String templatePage = itemTemplate + ".html";

        //3.使用模板引擎把Context数据写入静态模板中，最终生成一个静态页面
        //3.1 定义文件输出流
        PrintWriter writer = null;
        try {
            writer = new PrintWriter(new File(itemDir + "/" + spuId + ".html"));

            //3.2 使用模板引擎写出静态页面
            templateEngine.process(templatePage, context, writer);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            //注意：必须记得关闭输出流，否则后面无法删除该页面
            writer.close();
        }
    }

    // 删除静态页
    public void deleteStaticPage(Long spuId) {
        //1.读取文件
        //1.1 获取文件所在地理路径
        //1.2 获取文件
        String fileName = spuId + ".html";
        File file = new File(itemDir, fileName);

        //2删除文件
        if (file.exists()) {
            file.delete();
        }
    }

    // 秒杀
    public Boolean skill(Long skuid) {
        UserInfo user = UserHolder.getUser();
        if (user == null) {
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
        ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
        String skusList = valueOperations.get("SECKILL_SKUS_LIST");
        if (skusList == null) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        List<Sku> skus = JsonUtils.toList(skusList, Sku.class);
        Sku sku = null;
        for (int i = 0; i < skus.size(); i++) {
            sku = skus.get(i);
            if (sku.getId().equals(skuid)) {
                if (sku.getStock() - 1 >= 0) {
                    skus.get(i).setStock(sku.getStock() - 1);
                    valueOperations.set("SECKILL_SKUS_LIST", JsonUtils.toString(skus));
                    amqpTemplate.convertAndSend(
                            MQConstants.Exchange.SECOND_EXCHANGE_NAME,
                            MQConstants.RoutingKey.SECOND_SECKILL_KEY,
                            skuid + "," + user.getId());
                    return true;
                }
            }
        }
        return false;
    }


}
